﻿using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using SKIT.FlurlHttpClient.Wechat.Api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WomanMotion.WebApi.Wechat.HttpClients;
using WomanMotion.WebApi.Wechat.Options;
using WomanMotion.WebApi.Wechat.Repositories;
using WomanMotion.WebApi.Wechat.IService;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinMessageSubscribeSendRequest.Types;
using Microsoft.Extensions.Logging;

namespace WomanMotion.WebApi.Wechat.Service
{
    public class WechatCommon : IWechatCommon
    {
        private readonly IWechatApiHttpClientFactory _wechatApiHttpClientFactory;
        private readonly IWechatAccessTokenEntityRepository _wechatAccessTokenEntityRepository;
        private readonly WechatOptions _wechatOptions;
        private readonly ILogger _logger;

        public WechatCommon(IWechatAccessTokenEntityRepository wechatAccessTokenEntityRepository, IWechatApiHttpClientFactory wechatApiHttpClientFactory, IOptions<WechatOptions> wechatOptions, ILogger<WechatCommon> logger)
        {
            _wechatApiHttpClientFactory = wechatApiHttpClientFactory;
            _wechatAccessTokenEntityRepository = wechatAccessTokenEntityRepository;
            _wechatOptions = wechatOptions.Value;
            _logger = logger;
        }

        /// <summary>
        /// 根据用户code获取微信openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<KeyValuePair<int, string>> GetOpenidAsync(string code)
        {
            var entity = _wechatAccessTokenEntityRepository.FirstOrDefault();
            var request = new SnsJsCode2SessionRequest() { AccessToken = entity?.AccessToken, JsCode = code };
            var client = _wechatApiHttpClientFactory.Create();
            var res = await client.ExecuteSnsJsCode2SessionAsync(request);
            if (res.ErrorCode == 0)
            {
                var data = new KeyValuePair<int, string>(1, res.OpenId);
                return data;
            }
            else
            {
                var data = new KeyValuePair<int, string>(0, "errcode:" + res.ErrorCode + "  errmsg:" + res.ErrorMessage);
                return data;
            }
        }

        /// <summary>
        /// 推送订阅赛事信息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="templateId"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<KeyValuePair<int, string>> MatchSendMegAsync(string openid, string templateId, Dictionary<string, string> data)
        {
            //https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
            Dictionary<string, DataItem> msgdata = new Dictionary<string, DataItem>();
            foreach (var item in data)
            {
                msgdata.Add(item.Key, new DataItem() { Value = item.Value });
            }
            var entity = _wechatAccessTokenEntityRepository.FirstOrDefault();
            var request = new CgibinMessageSubscribeSendRequest() { AccessToken = entity?.AccessToken, ToUserOpenId = openid, TemplateId = templateId, MiniProgramPagePath = "pages/match/match", Data = msgdata };
            var client = _wechatApiHttpClientFactory.Create();
            var res = await client.ExecuteCgibinMessageSubscribeSendAsync(request);
            if (res.ErrorCode == 0)
            {
                var resdata = new KeyValuePair<int, string>(1, res.ErrorMessage);
                _logger.LogInformation("推送订阅消息成功");
                return resdata;
            }
            else
            {
                var resdata = new KeyValuePair<int, string>(0, "errcode:" + res.ErrorCode + "  errmsg:" + res.ErrorMessage);
                _logger.LogError("推送订阅消息成功失败" + "errcode:" + res.ErrorCode + "  errmsg:" + res.ErrorMessage);
                return resdata;
            }
        }
    }
}